-- lamp_upgraded
-- Created by zouyb Oct/21/2015
-- 成就：神灯升级

-- 内部函数声明
local whenLampUpgraded;

-- 注册神灯升级的回调
EventMgr.register("achievements/lamp_upgraded", event.LAMP_UPGRADED, function(args)
    whenLampUpgraded(args);
end);

-- 神灯升级的回调
whenLampUpgraded = function(args)
    -- 玩家不在迷宫中
    if not DungeonM.isInDungeon() then
        return;
    end

	-- 当前星级
	local star = args["star"];

    -- 获取当前所在的迷宫编号
    local dungeonId = DungeonM.getDungeonId();

    -- 遍历所有的子规则
    local ids = AchievementM.getIdsByRule("lamp_upgraded");

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == AchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        if not AchievementM.isBelongTo(id, dungeonId) then
            -- 不是该迷宫的成就
            return false;
        end

        local config = AchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg) == 'table' then
            -- 判断是否是对应星级
            if type(ruleArg["star"]) == 'number' and
                ruleArg["star"] > star then
                return false;
            end
        end	

        return true;
    end

    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            AchievementM.tryComplete(id, 1);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = AchievementM.query(id);

        local ruleArg = config["rule_arg"];
        local star   = ruleArg["star"];
        local desc    = config["desc"];

        desc = string.gsub(desc, "{0}", tostring(star));

        return desc;
    end,
};